package com.boyuan.huijiaoyu;

import java.util.ArrayList;
import java.util.List;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.boyuan.huijiaoyu.R;
import com.ender.android.stickylistheaders.SideBar;
import com.ender.android.stickylistheaders.SideBar.OnTouchingLetterChangedListener;
import com.ender.android.stickylistheaders.StickyListHeadersAdapter;
import com.ender.android.stickylistheaders.StickyListHeadersListView;
import com.magicsoft.app.entity.ContactPerson;
import com.magicsoft.app.helper.ChineseSort;
import com.magicsoft.app.helper.ChineseToLetter;
import com.magicsoft.app.helper.ContactHelper;
import com.magicsoft.app.helper.StringUtils;
import com.magicsoft.app.helper.ToastHelper;

/**
 * 通讯录选择好友
 * 
 * @author cheng
 * 
 */
public class SelectFriendFromContactsActivity extends BaseActivity implements
		OnClickListener {

	private static final String TAG = "SelectFriendFromContactsActivity";

	private Button btnBack;

	private SideBar sideBar;
	// private TextView dialog;

	private StickyListHeadersListView listView;
	private List<ContactPerson> allContactList;
	private ContactsAdaper adaper;
	private ChineseToLetter convert;
	private Handler handler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_friend_from_contacts_activity);
		prepareView();
		handler.post(runnable);

		// prepareData();
	}

	private void prepareView() {

		allContactList = new ArrayList<ContactPerson>();

		convert = new ChineseToLetter();

		btnBack = (Button) findViewById(R.id.import_new_member_btnBack);
		btnBack.setOnClickListener(this);

		listView = (StickyListHeadersListView) findViewById(R.id.import_new_member_contacts_lists);

		adaper = new ContactsAdaper(getApplicationContext(), allContactList);

		listView.setAdapter(adaper);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
//				Intent intent = new Intent();
//				intent.putExtra("tel", allContactList.get(position).getMobile());
//				setResult(RESULT_OK, intent);
				Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+allContactList.get(position).getMobile()));  
                startActivity(intent);
				finish();
			}
		});

		sideBar = (SideBar) findViewById(R.id.sidrbar);
		// dialog = (TextView) findViewById(R.id.dialog);
		// sideBar.setTextView(dialog);

		// �����Ҳഥ������
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {

				int position = adaper.getPositionForSection(s.charAt(0));

				if (position != -1) {
					listView.setSelection(position);
				}

			}
		});

	}

	/**
	 * 获取通讯录
	 */
	Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			List<ContactPerson> datas = null;

			showLoading(getResources().getString(
					R.string.isbeing_read_addressbook));
			try {
				datas = ContactHelper
						.GetPhoneContact(SelectFriendFromContactsActivity.this);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (datas != null) {

				allContactList.clear();
				allContactList.addAll(datas);
				GetPinYin(allContactList);

				ChineseSort.sort(allContactList);// 首字母排序
			} else {
				ToastHelper.showMsg(getApplicationContext(), getResources()
						.getString(R.string.isnull_addressbook), true);
			}

			adaper.notifyDataSetChanged();
			hideLoading();

		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.import_new_member_btnBack:

			setResult(RESULT_CANCELED);
			finish();
			break;

		}

	}

	/**
	 * 获取首字母拼音
	 * 
	 * @param member
	 */
	private void GetPinYin(List<ContactPerson> contactPerson) {

		if (contactPerson == null) {
			return;
		}
		for (ContactPerson contactPerson2 : contactPerson) {
			contactPerson2.setPinyin("#");
			if (contactPerson2.getMembername().trim().length() > 0) {

				// String letters = convert.String2Alpha(contactPerson2
				// .getMembername());
				String letters = converterToPinYin(contactPerson2
						.getMembername());
				if (letters.length() > 0) {

					Log.i(TAG, letters);

					String key = letters.substring(0, 1);

					if (key.length() > 0) {

						contactPerson2.setPinyin(key.toUpperCase());

					}

				}

			}
		}
	}

	/**
	 * 汉语拼音转换工具
	 * 
	 * @param chinese
	 * @return
	 */
	private String converterToPinYin(String chinese) {
		String pinyinString = "";
		char[] charArray = chinese.toCharArray();
		// 根据需要定制输出格式，我用默认的即可
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);// 大写
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 无声调表示
		defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);// 用V表示特殊拼音ü的显示
		try {
			// 遍历数组，ASC码大于128进行转换
			for (int i = 0; i < charArray.length; i++) {
				if (charArray[i] > 128) {
					// charAt(0)取出首字母
					if (charArray[i] >= 0x4e00 && charArray[i] <= 0x9fa5) { // 判断是否中文
						pinyinString += PinyinHelper.toHanyuPinyinStringArray(
								charArray[i], defaultFormat)[0];
					} else { // 不是中文的打上未知，所以无法处理韩文日本等等其他文字
						pinyinString += "?";
					}
				} else {
					if (charArray[i] >= 97 && charArray[i] <= 122) {// 小写字母转换为大写字母
						pinyinString += Character.toUpperCase(charArray[i]);
					} else {
						pinyinString += charArray[i];
					}
				}
			}
			return pinyinString;
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			// e.printStackTrace();
			return "";
		}
	}

	private class ContactsAdaper extends BaseAdapter implements
			StickyListHeadersAdapter {

		Context context;
		List<ContactPerson> datas;
		LayoutInflater inflater;

		public ContactsAdaper(Context context, List<ContactPerson> datas) {

			this.context = context;
			this.datas = datas;

			inflater = LayoutInflater.from(context);

		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return datas.size();
		}

		@Override
		public ContactPerson getItem(int position) {
			// TODO Auto-generated method stub
			return datas.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			ContactPerson contactPerson = datas.get(position);

			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(
						R.layout.contacts_item, null);

				holder.textView = (TextView) convertView
						.findViewById(R.id.contacts_phonename);
				holder.tv_separaor = (TextView) convertView
						.findViewById(R.id.tv_separaor);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (datas.size() > (position + 1)
					&& (contactPerson.getPinyin()).equals(datas.get(
							position + 1).getPinyin())) {
				holder.tv_separaor.setVisibility(View.VISIBLE);
			} else {
				holder.tv_separaor.setVisibility(View.GONE);
			}

			holder.textView.setText(contactPerson.getMembername() + "  "
					+ contactPerson.getMobile());

			return convertView;
		}

		@Override
		public View getHeaderView(int position, View convertView,
				ViewGroup parent) {
			HeaderViewHolder holder;
			ContactPerson contactPerson = datas.get(position);
			if (convertView == null) {
				holder = new HeaderViewHolder();
				convertView = inflater.inflate(R.layout.member_list_header,
						parent, false);
				holder.text = (TextView) convertView.findViewById(R.id.name);
				convertView.setTag(holder);
			} else {
				holder = (HeaderViewHolder) convertView.getTag();
			}
			String headerText = contactPerson.getPinyin();
			if (headerText == null) {
				headerText = "";
			}
			if (StringUtils.isEmpty(headerText)) {
				headerText = "A";
			}

			holder.text.setText(headerText);

			return convertView;
		}

		@Override
		public long getHeaderId(int position) {
			ContactPerson contactPerson = datas.get(position);
			String headerText = contactPerson.getPinyin();
			if (headerText == null) {
				headerText = "";
			}
			if (StringUtils.isEmpty(headerText)) {
				headerText = "A";
			}
			return headerText.subSequence(0, 1).charAt(0);
		}

		class HeaderViewHolder {
			TextView text;

		}

		class ViewHolder {
			TextView textView;
			TextView tv_separaor;

		}

		/**
		 * ���ListView�ĵ�ǰλ�û�ȡ���������ĸ��Char asciiֵ
		 */
		public int getSectionForPosition(int position) {
			return datas.get(position).getPinyin().charAt(0);
		}

		/**
		 * ��ݷ��������ĸ��Char asciiֵ��ȡ���һ�γ��ָ�����ĸ��λ��
		 */
		public int getPositionForSection(int section) {
			for (int i = 0; i < getCount(); i++) {

				String sortStr = datas.get(i).getPinyin();

				char firstChar = sortStr.toUpperCase().charAt(0);
				if (firstChar == section) {
					return i;
				}
			}

			return -1;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (handler != null) {
			handler.removeCallbacks(runnable);
		}
	}

	@Override
	public void backClicked() {
		// TODO Auto-generated method stub
		isBackAllowed = true;
	}
}
